package com.wimcorp.magic.data.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.transaction.annotation.Transactional;

import com.wimcorp.magic.data.DeckData;
@Transactional
public class DeckDataDaoImpl implements DeckDataDao {

	@PersistenceContext
	private EntityManager entityManager;

	@Override
	public long saveOrUpdate(DeckData o) {
		if (o.getId() == null) {
			entityManager.persist(o);
			return o.getId();
		} else {
			return entityManager.merge(o).getId();
		}
	}

	@Override
	public DeckData getDeck(long id) {
		List<DeckData> decks = entityManager
				.createQuery("select d from DeckData d where id=:id", DeckData.class).setParameter("id", id)
				.getResultList();
		if (decks.size() > 0) {
			return decks.get(0);
		} else {
			return null;
		}
	}
	
	@Override
	public DeckData getDeck(String code) {
		List<DeckData> decks = entityManager
				.createQuery("select d from DeckData d where code=:code", DeckData.class).setParameter("code", code)
				.getResultList();
		if (decks.size() > 0) {
			return decks.get(0);
		} else {
			return null;
		}
	}

	@Override
	public List<DeckData> getAll() {
		List<DeckData> decks = entityManager
				.createQuery("select d from DeckData d", DeckData.class)
				.getResultList();
		return decks;
	}
	
	@Override
	public List<DeckData> getDeckNames() {
		List<DeckData> decks = entityManager
				.createQuery("select new DeckData(dd.code,dd.name) from DeckData dd order by dd.name", DeckData.class)
				.getResultList();
		return decks;
	}

}
